package com.dts.evaluate.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

import com.dts.evaluate.R;
import com.dts.evaluate.bean.PersonBroadBean;
import com.dts.evaluate.bean.Worker;
import com.dts.evaluate.common.Constants;
import com.dts.evaluate.controller.impl.DataImpl;
import com.dts.evaluate.controller.intf.DataInterface;
import com.dts.evaluate.ui.view.StrokeEditText;
import com.dts.evaluate.ui.view.TitleView;
import com.dts.evaluate.utils.LogUtil;
import com.dts.evaluate.utils.PreferencesUtils;
import com.dts.evaluate.utils.StringUtils;
import com.dts.evaluate.utils.TimeUtils;
import com.dts.evaluate.utils.ToastUtils;
import com.google.gson.Gson;
import com.lzy.okhttputils.callback.StringCallback;

import java.util.Calendar;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class PersonBroadActivity extends BaseActivity implements TitleView.OnBackClikListener, View.OnClickListener {

    @Bind(R.id.content_edittext)
    StrokeEditText contentEdittext;
    @Bind(R.id.start_time_textview)
    TextView startTimeTextview;
    @Bind(R.id.end_time_textview)
    TextView endTimeTextview;
    @Bind(R.id.sure_textview)
    TextView sureTextview;
    @Bind(R.id.cancel_textview)
    TextView cancelTextview;
    @Bind(R.id.resume_textview)
    TextView resumeTextview;
    @Bind(R.id.title_view)
    TitleView titleView;
    @Bind(R.id.phone_number_edittext)
    StrokeEditText phoneNumberEdittext;

    private Worker mWorker;
    private  PersonBroadBean personBroadBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_broad);
        ButterKnife.bind(this);



        //初始化控件
        initView();

        mWorker = (Worker) getIntent().getSerializableExtra(Constants.WORKER);
        if(mWorker == null){
            return;
        }
    }

    private void initView() {
        //设置 titleview 返回监听。和更换密码点击监听
        titleView.setOnBackClickListener(this);
        //确认按钮点击监听
        sureTextview.setOnClickListener(this);
        //取消按钮点击监听
        cancelTextview.setOnClickListener(this);
        //恢复办件按钮点击监听
        resumeTextview.setOnClickListener(this);
        //起始时间点击监听
        startTimeTextview.setOnClickListener(this);
        //截至时间点击监听
        endTimeTextview.setOnClickListener(this);

        //看有无个人公告
        String personBroadJson = PreferencesUtils.getString(this, Constants.PERSON_BROAD_BEAN,null);
        //无个人公告
        if(StringUtils.isBlank(personBroadJson)){
            return;
        }
        personBroadBean = new Gson().fromJson(personBroadJson,PersonBroadBean.class);
        String textReason = personBroadBean.getTxtreason();
        String beginTime = personBroadBean.getTxtbegintime();
        String endTime = personBroadBean.getTxtendtime();
        String tel = personBroadBean.getTxttel();

        contentEdittext.setText(textReason);
        startTimeTextview.setText(beginTime);
        endTimeTextview.setText(endTime);
        phoneNumberEdittext.setText(tel);

    }


    @Override
    public void onTitleViewClik(View v) {
        switch (v.getId()) {
            case R.id.back_textview:
                finish();
                break;
            case R.id.other_textview:
                //更改密码
                showUpdatePasswordDailog();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sure_textview:
                //检查个人公告输入格式是否正确，并提交到服务器和发布到平板
                checkInputContent();
                break;
            case R.id.cancel_textview:
                finish();
                break;
            case R.id.resume_textview:
                //取消个人公告
                cancelPersonBroad(personBroadBean);
                break;
            case R.id.start_time_textview:
                //显示选择起始时间对话框
                showDateTimeDailog((TextView) v);
                break;
            case R.id.end_time_textview:
                //显示选择截至时间对话框
                showDateTimeDailog((TextView) v);
                break;
        }
    }

    /**
     * 检查个人公告输入格式  是否正确，并提交到服务器 和发布到主界面
     */
    private void checkInputContent(){

        if(personBroadBean != null){
            showErrorDialog("","已经发布有个人公告，请先恢复办件");
            return;
        }

        String content = contentEdittext.getText().toString();
        String startTime = startTimeTextview.getText().toString();
        String endTime = endTimeTextview.getText().toString();
        String phoneNumber = phoneNumberEdittext.getText().toString();

        if(StringUtils.isBlank(content)){
            contentEdittext.setError(getResources().getString(R.string.content_cant_null));
            return;
        }
        if(StringUtils.isEmpty(startTime)){
            startTimeTextview.setError(getResources().getString(R.string.start_time_cant_null));
            ToastUtils.show(PersonBroadActivity.this,R.string.start_time_cant_null);
            return;
        }else {
            startTimeTextview.setError(null);
        }
        if(StringUtils.isEmpty(endTime)){
            endTimeTextview.setError(getResources().getString(R.string.end_time_cant_null));
            ToastUtils.show(PersonBroadActivity.this,R.string.end_time_cant_null);
            return;
        }else {
            endTimeTextview.setError(null);
        }
        if(TimeUtils.compare(startTime,endTime) > 0){
            ToastUtils.show(PersonBroadActivity.this,R.string.end_time_cant_less_than_start_time);
            endTimeTextview.setError(getResources().getString(R.string.end_time_cant_less_than_start_time));
            return;
        }

        if(StringUtils.isEmpty(phoneNumber)){
            phoneNumberEdittext.setError(getResources().getString(R.string.phone_number_cant_null));
            return;
        }

        // 提交个人公告到服务器
        PersonBroadBean personBroadBean = new PersonBroadBean();
        personBroadBean.setTxtreason(content);
        personBroadBean.setTxtbegintime(startTime);
        personBroadBean.setTxtendtime(endTime);
        personBroadBean.setTxttel(phoneNumber);

        publishPersonBroad(personBroadBean);
    }


    /**
     * 发布个人公告到服务器
     * @param personBroadBean
     */
    private void publishPersonBroad(final PersonBroadBean personBroadBean){
        //向服务器提交公告
        showProgress();
        DataInterface dataInterface = new DataImpl();
        dataInterface.publishPersonBroad(Constants.COMIMIT_PERSON_BRAOD_URL
                , Constants.PUBLISH_TYPE
                , String.valueOf(mWorker.getTableIdOfGscUser())
                , personBroadBean.getTxtbegintime() + ":00.000"
                , personBroadBean.getTxtendtime() + ":00.000"
                , personBroadBean.getTxttel()
                , personBroadBean.getTxtreason(),
                new StringCallback() {
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                        hideProgress();
                        showErrorDialog("","发布个人公告失败");
                    }

                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        LogUtil.v("s:"+s);
                       hideProgress();
                        try {
                            int id = Integer.parseInt(s);
                            if (id == -1) {
                                showErrorDialog("发布个人公告","发布公告失败");
                            }else {
                                //将个人公告内容，放到本地
                                personBroadBean.setId(id);
                                String json = new Gson().toJson(personBroadBean);
                                PreferencesUtils.putString(PersonBroadActivity.this,Constants.PERSON_BROAD_BEAN,json);

                                //携带数据返回ManiActivity
                                Intent intent = new Intent();
                                intent.putExtra(Constants.PERSON_BROAD_BEAN,personBroadBean);
                                setResult(RESULT_OK,intent);
                                finish();
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }, this);

    }

    /**
     * 取消个人公告，恢复办件
     * @param personBroadBean
     */
    private void cancelPersonBroad(PersonBroadBean personBroadBean){
        if(personBroadBean == null){
            showErrorDialog("","没有发布个人公告");
            return;
        }
        int id = personBroadBean.getId();
        showProgress();
        DataInterface dataInterface = new DataImpl();
        dataInterface.cancelPersonBroad(Constants.COMIMIT_PERSON_BRAOD_URL, Constants.CANCEL_TYPE, String.valueOf(id), new StringCallback() {

            @Override
            public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                super.onError(isFromCache, call, response, e);
                hideProgress();
                showErrorDialog("",getResources().getString(R.string.dialog_net_error));
            }

            @Override
            public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                LogUtil.v("result:" + s);
                hideProgress();
                PreferencesUtils.putString(PersonBroadActivity.this,Constants.PERSON_BROAD_BEAN,"");
                Intent intent = new Intent();
                intent.putExtra(Constants.IS_RECOVERY,true);
                setResult(RESULT_OK,intent);
                finish();
            }
        }, this);
    }




    private AlertDialog mDialog;//更换密码对话框
    /**
     * 显示更换密码对话框
     */
    private void showUpdatePasswordDailog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.update_password);

        //设置dialog自定义view
        LayoutInflater inflater = LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.dialog_update_password_layout,null);
        final EditText origPasswordEditText = (EditText) v.findViewById(R.id.orig_password_edittext);
        final EditText newPasswordEditText = (EditText) v.findViewById(R.id.new_password_edittext);
        TextView sureTextView = (TextView) v.findViewById(R.id.sure_textview);
        TextView cancelTextView = (TextView) v.findViewById(R.id.cancel_textview);

        builder.setView(v);

        //设置确认点击监听
        sureTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String origPassword = origPasswordEditText.getText().toString();
                String newPassword = newPasswordEditText.getText().toString();
                //源密码为空
                if(StringUtils.isEmpty(origPassword)){
                    origPasswordEditText.setError(getResources().getString(R.string.orig_password_cant_null));
                    return;
                }
                //原密码错误
                String nativePassword = PreferencesUtils.getString(PersonBroadActivity.this,Constants.PASSWORD,"");
                if(!StringUtils.isBlank(nativePassword) && !StringUtils.isEquals(nativePassword,origPassword)){
                    origPasswordEditText.setError(getResources().getString(R.string.orig_password_error));
                    ToastUtils.show(PersonBroadActivity.this,R.string.orig_password_error);
                    return;
                }
                //新密码为空
                if(StringUtils.isEmpty(newPassword)){
                    newPasswordEditText.setError(getResources().getString(R.string.new_password_cant_null));
                    return;
                }
                //新密码和原密码相同了
                if(StringUtils.isEquals(origPassword,newPassword)){
                    newPasswordEditText.setError(getResources().getString(R.string.password_cant_equals));
                }
                if(!StringUtils.isEquals(origPassword,newPassword)){
                    //提交新密码到服务器
                    updatePassword(newPassword);

                }
            }
        });

        //设置取消点击监听
        cancelTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mDialog != null){
                    mDialog.dismiss();
                }
            }
        });

        mDialog = builder.create();
        mDialog.show();

    }

    /**
     *  提交密码到服务器
     */
    private void updatePassword(final String newPassword){
        DataInterface dataInterface = new DataImpl();
        showProgress();
        dataInterface.updatePassword(Constants.UPDATE_PASSWORD_URL, String.valueOf(mWorker.getTableIdOfGscUser()), newPassword, new StringCallback() {
            @Override
            public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                super.onError(isFromCache, call, response, e);
                hideProgress();
                showErrorDialog("",getResources().getString(R.string.dialog_net_error));
            }

            @Override
            public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                hideProgress();
                if(StringUtils.isBlank(s)){
                    return;
                }
                try {
                    int code = Integer.parseInt(s);
                    if (code == 200) {

                        showSuccessDialog("",getResources().getString(R.string.update_password_success));
                        //将新密码存放到sharePreference
                        PreferencesUtils.putString(PersonBroadActivity.this,Constants.PASSWORD,newPassword);

                        if(mDialog != null && mDialog.isShowing()){
                            mDialog.dismiss();
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }, this);
    }

    /**
     * 显示日期和时间对话框
     *
     * @param tv
     */
    private void showDateTimeDailog(final TextView tv) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        View view = LayoutInflater.from(this).inflate(R.layout.date_time_dialog_layout, null);
        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
        final TimePicker timePicker = (TimePicker) view.findViewById(R.id.time_picker);
        initDateAndTime(datePicker, timePicker);
        builder.setView(view);
        switch (tv.getId()) {
            case R.id.start_time_textview:
                builder.setTitle(getResources().getString(R.string.please_choice_start_time));
                break;
            case R.id.end_time_textview:
                builder.setTitle(getResources().getString(R.string.please_choice_end_timetime));
                break;
        }
        builder.setPositiveButton(getResources().getString(R.string.sure), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                StringBuffer sb = new StringBuffer();
                sb.append(String.format("%d-%02d-%02d",
                        datePicker.getYear(),
                        datePicker.getMonth() + 1,
                        datePicker.getDayOfMonth()));
                sb.append(" ");
                sb.append(timePicker.getCurrentHour())
                        .append(":").append(timePicker.getCurrentMinute());
                tv.setText(sb);
                tv.setError(null);
                dialog.cancel();
            }
        });

        builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.create().show();
    }

    /**
     * 初始化DatePicker和TimePicker
     *
     * @param datePicker
     * @param timePicker
     */
    private void initDateAndTime(DatePicker datePicker, TimePicker timePicker) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);
        timePicker.setIs24HourView(true);
        timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
        timePicker.setCurrentMinute(cal.get(Calendar.MINUTE));

    }

}
